import random

class QuestionGenerator:
    def __init__(self, operations, difficulty, count):
        self.operations = operations
        self.difficulty = difficulty
        self.count = count
        self.questions = []
        self.answers = []

    def generate_numbers(self):
        """根据难度生成数字"""
        if self.difficulty == 'easy':
            return random.randint(1, 10), random.randint(1, 10)
        elif self.difficulty == 'medium':
            return random.randint(10, 50), random.randint(10, 50)
        else:  # hard
            return random.randint(50, 100), random.randint(50, 100)

    def generate_division_numbers(self):
        """特别处理除法，确保能整除且答案合理"""
        if self.difficulty == 'easy':
            b = random.randint(1, 10)
            a = b * random.randint(1, 10)
        elif self.difficulty == 'medium':
            b = random.randint(2, 20)
            a = b * random.randint(2, 20)
        else:  # hard
            b = random.randint(2, 50)
            a = b * random.randint(2, 50)
        return a, b

    def generate_question(self):
        """生成单个题目"""
        operation = random.choice(self.operations)
        
        if operation == 'division':
            a, b = self.generate_division_numbers()
            question = f"{a} ÷ {b} = "
            answer = a // b
        else:
            a, b = self.generate_numbers()
            if operation == 'addition':
                question = f"{a} + {b} = "
                answer = a + b
            elif operation == 'subtraction':
                if a < b:  # 确保减法结果为正数
                    a, b = b, a
                question = f"{a} - {b} = "
                answer = a - b
            else:  # multiplication
                question = f"{a} × {b} = "
                answer = a * b
        
        return question, answer

    def generate_questions(self):
        """生成所有题目"""
        for _ in range(self.count):
            question, answer = self.generate_question()
            self.questions.append(question)
            self.answers.append(answer)

        return self.questions, self.answers

def generate_exercise(operations, difficulty, count):
    """生成练习题的主函数"""
    if isinstance(operations, str):
        operations = [operations]
    generator = QuestionGenerator(operations, difficulty, int(count))
    return generator.generate_questions()
